// COS 上传图片、视频方法
import COS from './cos-wx-sdk-v5'
import dayjs from 'dayjs';
import {
    COS_CONF
} from '../constants/common';
import {
    isObject,
    randomString
} from './utils';
import {
    chooseImage,
    getImageInfo,
    chooseVideo,
    getVideoInfo,
    uploadFile,
    showLoading,
    hideLoading,
    tipSuccess,
    tipError,
    canIUse
} from './env';
import {
    getCosAuthorization
} from '../api/common';

var cos = new COS({
    // ForcePathStyle: true, // 如果使用了很多存储桶，可以通过打开后缀式，减少配置白名单域名数量，请求时会用地域域名
    getAuthorization: function (options, callback) {
        getCosAuthorization().then(cosAuthorization => {
            if (!cosAuthorization || !cosAuthorization.credentials) {
                tipError("bucket credentials invalid");
                return
            }
            callback({
                TmpSecretId: cosAuthorization.credentials.tmpSecretId,
                TmpSecretKey: cosAuthorization.credentials.tmpSecretKey,
                XCosSecurityToken: cosAuthorization.credentials.sessionToken,
                ExpiredTime: cosAuthorization.credentials.expiredTime, // 时间戳，单位秒，如：1580000900
            });
        })
    }
});

// 上传图片 type 业务类型
const uploadImage = async (type, file) => {
    console.log('cos uploadImage...')
    if (!file) file = (await chooseImage())[0];
    const fileInfo = await getImageInfo(isObject(file) ? file.url : file);
    const key = `${type}_${dayjs().format('YYYYMMDD')}_${randomString(12)}.${fileInfo.type === 'jpeg' ? 'jpg' : fileInfo.type}`;
    showLoading('上传中...');
    const uploadKey = await uploadFileInBucket({
        key,
        file
    })
    if (uploadKey) {
        hideLoading();
        tipSuccess('上传成功');
    }
    return {
        url: `${uploadKey}`
    }
};

// 上传视频 type 业务类型
const uploadVideo = async (type, file) => {
    if (!file) file = await chooseVideo();
    let fileInfo = {
        type: 'mp4'
    };
    if (canIUse('getVideoInfo')) {
        fileInfo = await getVideoInfo(isObject(file) ? file.url : file);
    }
    const key = `${type}_${dayjs().format('YYYYMMDD')}_${randomString(12)}.${fileInfo.type}`;
    showLoading('上传中...');
    const uploadKey = await uploadFileInBucket({
        key,
        file,
        filetype: 'video'
    })
    if (uploadKey) {
        hideLoading();
        tipSuccess('上传成功');
    }
    return {
        url: `${uploadKey}`
    }
};

const uploadFileInBucket = async ({
    file,
    key,
    filetype = 'image'
}) => {
    const filePath = isObject(file) ? file.url : file
    return new Promise(function (resolve, reject) {
        cos.postObject({
            Bucket: COS_CONF.bucket,
            Region: COS_CONF.region,
            Key: key,
            FilePath: filePath,
            onProgress: function (info) {
                console.log(JSON.stringify(info));
            }
        }, function (err, data) {
            if (err) {
                tipError(err || 'cos上传错误')
                reject(err)
                return
            }
            resolve(key)
        });
    })
}


module.exports = {
    uploadImage,
    uploadVideo,
};